/** 
* Define th emain controller which manage current user, parameters, translations and menu behavior
*/
app.controller('maincontroller', ['$rootScope', 'userServices', function($rootScope, userServices)
{
	$rootScope.currentUser = undefined;
	
	/**
	* Set the current user
	*/
	$rootScope.setCurrentUser = function(data)
	{
		console.info("setCurrentUser - called with data : " + data); 
		
		try
		{
			if(typeof(Storage) !== undefined) 
			{
				localStorage.setItem("CurrentUser", JSON.stringify(data));
			} 
			else 
			{
				$cookieStore.put("CurrentUser", JSON.stringify(data));
			}
		}
		catch(exception)
		{
			console.error(exception.message);
		}

		$rootScope.$broadcast('currentUser', {
		  user: data 
		});
		$rootScope.currentUser = data;
	};
	
	/**
	* Get the current user
	*/
	$rootScope.getCurrentUser = function()
	{
		try
		{
			if(typeof(Storage) !== "undefined") 
			{
				$rootScope.currentUser = JSON.parse(localStorage.getItem("CurrentUser"));
			} 
			else 
			{
				$rootScope.currentUser = JSON.parse($cookieStore.get('CurrentUser'));
			}
		}
		catch(err)
		{
			$rootScope.currentUser = undefined;
		}
		return $rootScope.currentUser;
	};
	
	/**
	* Destroy the current user
	*/
	$rootScope.removeCurrentUser = function()
	{
		console.info("removeCurrentUser - called"); 
		if(typeof(Storage) !== undefined) 
		{
			$rootScope.currentUser = localStorage.removeItem("CurrentUser");
		} 
		else 
		{
			$rootScope.currentUser = $cookieStore.remove('CurrentUser');
		}
		$rootScope.$broadcast('currentUser', {
		  user: undefined 
		});
		$rootScope.currentUser = undefined;
	};
	
	$rootScope.$on('$routeChangeStart', function(event, curr, prev) { 
		if (!userServices.isLoggedIn()) {
			console.log('User is denied');
			event.preventDefault();
			$location.path('/login');
		}
		else {
			console.log('User is allow');
		}
	
		$('.preloader').show();
	});
	
	$rootScope.$on('$routeChangeSuccess', function(event, curr, prev) { 
		$('.preloader').hide();
	});
	
	var parametersLoader = $.getJSON("parameters.json", function() {
		})
		.done(function(json) {
			toolsServices.setParameters(json);
			console.debug('parameters file loaded');
		})
		.fail(function(parametersLoader, textStatus, error) {
			alert( "error " + error + " " + textStatus);
		})
		.always(function() {
			console.debug('load parameters file finished');
	});
}]);
